<?php
/*
 * Author: Quan Van Sinh
 * Email : sinhvnb@vietnambiz.com
 * Mobile: 0972405165
 */
function uploadImages() {
    global $CONFIG;
    $images = $_FILES['images'];
    if($_GET['forModule']=='property') {
        $module = $_GET['forModule'];
        $thumbSize = $CONFIG['thumb_size_property'];
    }else {
        $module = 'news';
        $thumbSize = $CONFIG['thumb_size_news'];
    }
    $upload_dir = $CONFIG ['upload_dir'].'/images/'.$module.'/sl-'.$_SESSION['adlogin']["id"].'/'.date("Y").'/'.date("m");
    $now = time();
    if($images['size'][0]!='') {
        for($i=0;$i<count($images['size']);$i++) {
            if ((($images["type"][$i] == 'image/gif') || ($images["type"][$i] == 'image/jpeg')
                || ($images["type"][$i] == 'image/png') || ($images["type"][$i] == 'image/jpg')) && ($images["size"][$i] < 5000000)) {
                $arrImageNameExplode = explode('.', $images["name"][$i]);
                $imageExtention = $arrImageNameExplode[(count($arrImageNameExplode)-1)];
                $filename = $now.'-'.rand(0,999999).'.'.strtolower($imageExtention);
                if (!file_exists($upload_dir)) {
                    if(!mkdir($upload_dir, 0777,true)) {
                        $CONFIG["error_message"] .= "<li>Không thể tạo thư mục, kiểm tra quyền của bạn.</li>";
                    }
                }
                if (move_uploaded_file($images["tmp_name"][$i],$upload_dir."/".$filename)) {
                    for($s=0;$s<count($thumbSize);$s++) {// start create thumbnail
                        $upload_dir_thumb = $upload_dir.'/thumb-'.$thumbSize[$s];
                        if (!file_exists($upload_dir_thumb)) {
                            if(!mkdir($upload_dir_thumb, 0777,true)) {
                                $CONFIG["error_message"] .= "<li>Không thể tạo thư mục, kiểm tra quyền của bạn.</li>";
                            }
                        }
                        $wh = explode('-',$thumbSize[$s]);
                        $thumbnail_width = $wh[0];
                        $thumbnail_heigh = $wh[1];
                        //create thumb
                        include_once (ADMIN_LIBRARY_DIR."/phpThumb/ThumbLib.inc.php");
                        $options = array('resizeUp' => true, 'jpegQuality'=>88);
                        $thumb = PhpThumbFactory::create($upload_dir."/".$filename, $options);
                        $thumb->adaptiveResize($thumbnail_width+5, $thumbnail_heigh+5);
                        $thumb->cropFromCenter($thumbnail_width, $thumbnail_heigh);
                        $thumb->save($upload_dir_thumb.'/'.$filename,'jpg');
                    }
                    $CONFIG["success_message"] .= "<li>".$images["name"][$i]." tải lên thành công!.</li>";
                }else {
                    $CONFIG["error_message"] .= "<li>Lỗi, không thể tải lên file: ".$images["name"][$i].'</li>';
                }
            }else {
                $CONFIG["error_message"] .= "<li>File không đúng ".$images['name'][$i].'</li>';
            }
        }
        $CONFIG["success_message"] .= "<li>Thêm mới ảnh thành công!</li>";
    }else {
        $CONFIG["error_message"] .= "<li>Bạn chưa chọn file để tải lên! ".$images['name'][$i].'</li>';
    }
}
// cho ban. biet ban dang o thu muc nao
function listDirPath() {
    global $CONFIG;
    if($_GET['forModule']=='property') {
        $module = $_GET['forModule'];
    }else {
        $module = 'news';
    }
    //    $dir = $CONFIG ['upload_dir'].'/images/'.$module.'/sl-'.$_SESSION['adlogin']["id"].'/';
    $dir = $CONFIG ['upload_dir'].'/images/'.$module.'/';
    if(isset($_GET['dir']) && $_GET['dir']!='') {
        $dir .= $_GET['dir'];
    }
    echo '<ul>';
    echo '<li><a href="'.get_string_url(array('dir')).'">Root</a></li>';
    $pos = strpos($_GET['dir'], '/');
    $arrDir = explode('/', $_GET['dir']);
    $username = getUserNameById($arrDir[0]);
    if(isset($_GET['dir']) && $_GET['dir']!='') {
        if($pos==FALSE) {
            $username = getUserNameById($_GET['dir']);
            echo '<li><a href="'.get_string_url(array('dir')).'&dir='.$_GET['dir'].'">'.$username.'</a></li>';
        }else {
            echo '<li><a href="'.get_string_url(array('dir')).'&dir='.$arrDir[0].'">'.$username.'</a></li>';
            echo '<li><a href="'.get_string_url(array('dir')).'&dir='.$arrDir[0].'/'.$arrDir[1].'">'.$arrDir[1].'</a></li>';
            echo '<li class="last">'.$arrDir[2].'</li>';
        }
    }
    echo '</ul>';
}
//liet ke thu muc hoac liet ke anh?
function listDir() {
    global $CONFIG,$CONFIG;
    if($_GET['forModule']=='property') {
        $module = $_GET['forModule'];
        $thumbSize = $CONFIG['thumb_size_property'];
    }else {
        $module = 'news';
        $thumbSize = $CONFIG['thumb_size_news'];
    }
    //$imageUrl = 'uploads/images/'.$module.'/sl-'.$_SESSION['adlogin']["id"];
    $imageUrl = 'uploads/images/'.$module;
    $defaultThumbDir = 'thumb-'.$thumbSize[0];
    //$dir = $CONFIG ['upload_dir'].'/images/'.$module.'/sl-'.$_SESSION['adlogin']["id"].'/';
    $dir = $CONFIG ['upload_dir'].'/images/'.$module.'/';
    $arrIgnore = Array('.','..','Thumbs.db','.svn');
    if(isset($_GET['dir']) && $_GET['dir']!='') {
        $dir .= $_GET['dir'];
    }
    $arrDir = explode('/', $_GET['dir']);
    if(count($arrDir)==3) {// vao trong thang' list images
        if(is_dir($dir)) {
            $handle = opendir($dir);
            if($handle) {
                while(($file = readdir($handle)) !== false) {
                    if(!in_array($file, $arrIgnore) && is_file($dir.'/'.$file)) {
                        if(isset($_GET['position']) && $_GET['position']=='content') {
                            echo '<img class="imagesContextAction" onclick="toImages(\'/'.$imageUrl.'/'.$arrDir[0].'/'.$arrDir[1].'/'.$arrDir[2].'/'.$file.'\');" style="border:3px solid #CCC;cursor: pointer;" src="/'.$imageUrl.'/'.$_GET['dir'].'/'.$defaultThumbDir.'/'.$file.'" alt="'.$file.'"/>'."\n";
                        }else {
                            echo '<img class="imagesContextAction" onclick="toImages(\'/'.$imageUrl.'/'.$_GET['dir'].'/'.$defaultThumbDir.'/'.$file.'\');" style="border:3px solid #CCC;cursor: pointer;" src="/'.$imageUrl.'/'.$_GET['dir'].'/'.$defaultThumbDir.'/'.$file.'" alt="'.$file.'"/>'."\n";
                        }
                    }
                }
            }
            closedir($handle);
        }
    }else { //vao trong nam, list month
        if(is_dir($dir)) {
            $handle = opendir($dir);
            if($handle) {
                while(($file = readdir($handle)) !== false) {
                    $pos = strpos($file, '.jp');
                    $pos1 = strpos($file, '.bm');
                    $pos2 = strpos($file, '.gi');
                    $pos3 = strpos($file, '.pn');
                    if(!in_array($file, $arrIgnore) && $pos==FALSE && $pos1==FALSE && $pos2==FALSE && $pos3==FALSE) {
                        if(isset($_GET['dir']) && $_GET['dir']!='') {
                            echo '<a href="'.get_string_url(array('action','dir')).'&dir='.$_GET['dir'].'/'.$file.'">'.$file.'</a>&nbsp;&nbsp;';
                        }else {
                            $username = getUserNameById($file);
                            echo '<a href="'.get_string_url(array('action','dir')).'&dir='.$file.'">'.$username.'</a>&nbsp;&nbsp;';
                        }
                    }
                }
            }
            closedir($handle);
        }
    }

}

function deleteImage() {
    global $CONFIG;
    $delDir = $_REQUEST['delDir'];
    $filename = basename($_REQUEST['filename']);
    if($_GET['forModule']=='property') {
        $module = $_GET['forModule'];
        $thumbSize = $CONFIG['thumb_size_property'];
    }else {
        $module = 'news';
        $thumbSize = $CONFIG['thumb_size_news'];
    }
    //    $upload_dir = $CONFIG ['upload_dir'].'/images/'.$module.'/sl-'.$_SESSION['adlogin']["id"].$delDir;
    $upload_dir = $CONFIG ['upload_dir'].'/images/'.$module.$delDir;
    if(file_exists($upload_dir.'/'.$filename)) {
        unlink($upload_dir.'/'.$filename);
    }
    for($s=0;$s<count($thumbSize);$s++) {// start create thumbnail
        $upload_dir_thumb = $upload_dir.'/thumb-'.$thumbSize[$s];
        if(file_exists($upload_dir_thumb.'/'.$filename)) {
            unlink($upload_dir_thumb.'/'.$filename);
        }
    }
//$CONFIG["success_message"] .= "<li>Delete image successful!.</li>";
}

function getUserNameById($strUserId) {
    global $db;
    $arrUserId = explode('-', $strUserId);
    if(intval($arrUserId[1])>0) {
        if($arrUserId[0]=='sl') {
            $userId = intval($arrUserId[1]);
            $sql = "SELECT username FROM admin WHERE id=$userId";
            $rs = $db->query_first($sql);
            return $rs['username'];
        }elseif($arrUserId[0]=='pub'){
            $memId = intval($arrUserId[1]);
            $sql = "SELECT username FROM members WHERE mem_id=$memId";
            $rs = $db->query_first($sql);
            return $rs['username'];
        }else{
            return 'no-username';
        }
    }else{
        return 'no-username';
    }
}

?>
